package com.example.composestudy.router.part1.home

import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import androidx.navigation.NamedNavArgument
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.example.composestudy.router.RouterConfig
import com.google.gson.Gson
import kotlinx.parcelize.Parcelize

val gson = Gson()

object HomeDirection2 {
    @Parcelize
    data class User(
        val name: String,
        val age: Int,
    ) : Parcelable

    const val route = "${RouterConfig.HOME}/{${RouterConfig.HOME_ARG_USER}}"

    val arguments: List<NamedNavArgument> = listOf(
//        navArgument(RouterConfig.HOME_ARG_USER) {
//            type = object : NavType<User>(false) {
//                override val name: String
//                    get() = "HomeArgs"
//
//                override fun get(bundle: Bundle, key: String): User? {
//                    return bundle.getParcelable(key) as User?
//                }
//
//                override fun parseValue(value: String): User {
//                    return gson.fromJson(value, User::class.java)
//                }
//
//                override fun put(bundle: Bundle, key: String, value: User) {
//                    bundle.putParcelable(key, value)
//                }
//            }
//        }
        navArgument(RouterConfig.HOME_ARG_USER) {
            type = NavType.StringType
        }
    )

    fun parsArguments(entry: NavBackStackEntry): User {
        //return entry.arguments?.getParcelable(RouterConfig.HOME_ARG_USER)!!
        val json = entry.arguments?.getString(RouterConfig.HOME_ARG_USER)!!
        return gson.fromJson(json, User::class.java)
    }

    fun toHomePager(user: User): String {
        return "${RouterConfig.HOME}/${Uri.encode(gson.toJson(user))}"
    }
}